// request拦截器
import axios from 'axios'

// 创建axios实例
const service = axios.create({
  timeout: 30000 // 请求超时时间
})
let serviceTips = '服务器超时'

// request拦截器
service.interceptors.request.use(
  config => {
    const value = window.localStorage.getItem('REC-TOKEN')
    if (value) {
      config.headers['rec-token'] = value
    }
    return config
  },
  err => {
    return Promise.reject(err)
  }
)

// http response 服务器响应拦截器
service.interceptors.response.use(
  response => {
    return response
  },
  error => {
    if (error.response) {
      switch (error.response.status) {
        case 401:
          error.response.data = '登陆超时，重新登陆'
          break
        case 404:
          error.response.data = '资源不存在'
          break
        case 415:
          error.response.data = '请求type有误'
          break
        case 500:
          error.response.data = error.response.data.message
          break
      }
      serviceTips = error.response.data
    }
    return Promise.reject(serviceTips)
  }
)
export default service
